package com.example.wzviewer.ui;

import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.view.View;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.PopupMenu;

import androidx.media3.common.C;
import androidx.media3.common.Player;


import com.example.wzviewer.R;
import com.example.wzviewer.data.VideoChooser;
import com.example.wzviewer.util.FfprobeLite;
import com.example.wzviewer.widget.Media3VideoView;
import com.gyf.immersionbar.BarHide;
import com.gyf.immersionbar.ImmersionBar;

import java.util.Locale;

public class PlayerActivity extends AppCompatActivity implements View.OnClickListener{

    //定义视频视图
    private Media3VideoView videoView;
    private ImageView btnPlay;
    private ImageView btnSettings;
    private TextView tvDuration;
    private TextView tvInfo;    //视频详细信息

    private ImageView btn_select;
    private VideoChooser videoChooser; //新增，视频选择器



    @Override
    protected void onCreate(Bundle savedInstanceState) {

        //保持屏幕常亮
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
        //隐藏状态栏 需添加ImmersionBar依赖
        ImmersionBar.with(this).hideBar(BarHide.FLAG_HIDE_STATUS_BAR).init();

        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_player);
        videoView = findViewById(R.id.player_view);

        videoView.play(Uri.parse("asset:///video/720p_2.mp4"));
        //videoView.play(Uri.parse("https://test-videos.co.uk/vids/bigbuckbunny/mp4/h264/720/Big_Buck_Bunny_720_10s_1MB.mp4"));

        btnPlay = (ImageView) videoView.findInController(R.id.btn_play);
        btnPlay.setOnClickListener(this);

        btnSettings=(ImageView) videoView.findInController(R.id.exo_settings);
        //拿到exo_settings按钮绑定监点击事件
        btnSettings.setOnClickListener(this);

        //视频总时长
        tvDuration = (TextView) videoView.findInController(R.id.video_duration);

        tvInfo = (TextView) videoView.findInController(R.id.video_info);

        //初始化选择器：把“选中的 Uri”交给播放器播放
        videoChooser = new VideoChooser(this, uri -> {
            videoView.play(uri);
            // 播起来后，STATE_READY 会自动触发 ffprobe 信息刷新（见下面监听）
        });

        btn_select = (ImageView) videoView.findInController(R.id.btn_select);
        if (btn_select!=null){
            btn_select.setOnClickListener(this);    //设置点击监听事件
        }

        //给视频播放完毕添加监听状态，播放完毕后切换按钮图标
        videoView.addPlayerListener(new Player.Listener() {

            //初始时正在播放默认暂停按钮图标
            @Override
            public void onIsPlayingChanged(boolean isPlaying) {
                btnPlay.setImageResource(isPlaying ? R.mipmap.video_pause : R.mipmap.video_play);
            }

            //获得视频总时长，等播放器准备好后更新时长
            @Override
            public void onPlaybackStateChanged(int playbackState) {
                if (playbackState == Player.STATE_READY) {
                    // 视频准备就绪，更新时长
                    long duration = videoView.getDuration();
                    if (duration != C.TIME_UNSET) {
                        String formatted = formatTime(duration);    //通过formatTime方法格式化时长
                        tvDuration.setText(formatted);
                    }

                    if (!videoView.isPlaying()){
                        btnPlay.setImageResource(R.mipmap.video_play);
                    }

                    // 通过 ffprobe 只获取：名称 + 分辨率（极快）
                    Uri uri = videoView.getCurrentUri();
                    if (uri != null) {
                        FfprobeLite.probeNameAndSize(PlayerActivity.this, uri, new FfprobeLite.Callback() {
                            @Override public void onSuccess(FfprobeLite.Result r) {
                                runOnUiThread(() -> {
                                    String size = (r.width>0 && r.height>0)
                                            ? (r.width + "x" + r.height) : "-";
                                    String text = "名称: " + safe(r.name) + "\n" +
                                            "分辨率: " + size;
                                    if (tvInfo != null) tvInfo.setText(text);
                                });
                            }
                            @Override public void onError(String msg) {
                                runOnUiThread(() -> {
                                    if (tvInfo != null) tvInfo.setText("获取视频信息失败：\n" + msg);
                                });
                            }
                        });

                    }


                }
                /*if (playbackState == Player.STATE_ENDED) {
                    btnPlay.setImageResource(R.mipmap.video_play);
                }*/

            } //onIsPlayingChanged

        });  //addPlayerListener


    }


    private static String safe(String s) { return s == null ? "-" : s; }

    //格式化时间
    private String formatTime(long millis){
        long totalSeconds = millis / 1000;
        long seconds = totalSeconds % 60;
        long minutes = (totalSeconds / 60) % 60;
        long hours   = totalSeconds / 3600;

        if (hours > 0) {
            return String.format(Locale.getDefault(), "%d:%02d:%02d", hours, minutes, seconds);
        } else {
            return String.format(Locale.getDefault(), "%02d:%02d", minutes, seconds);
        }
    }


    @Override
    public void onClick(View v) {
        if (v.getId() == R.id.btn_play) {

            //如果视频播放完毕，回到开头
            if (videoView.getPlaybackState()==Player.STATE_ENDED){
                videoView.seekTo(0);
                videoView.play();
                btnPlay.setImageResource(R.mipmap.video_pause);
                return;
            }

            if (videoView.isPlaying()) {
                videoView.pause();
                btnPlay.setImageResource(R.mipmap.video_play);
            } else {
                videoView.play();
                btnPlay.setImageResource(R.mipmap.video_pause);
            }

        }

        //设置按钮被点击后显示弹窗
        if(v.getId()==R.id.exo_settings){
            System.out.println("设置被点击了");
            PopupMenu menu = new PopupMenu(this, v);
            menu.getMenu().add(0, 1, 0, "重叠对比");
            menu.getMenu().add(0, 2, 1, "左右对比");
            menu.getMenu().add(0, 3, 2, "Split 对比");

            // 先不写业务，直接吃掉点击事件返回 true
            menu.setOnMenuItemClickListener(item -> {
                switch (item.getItemId()) {
                    case 1: /* TODO 重叠对比 */ break;
                    case 2: /* TODO 左右对比 */ break;
                    case 3: /* TODO Split 对比 */ break;
                }
                return true;
            });
            menu.show();    //显示按钮
        }

        if (v.getId()==R.id.btn_select){
            videoChooser.show();
        }

    }

}
